const base = require("./db")

let socketIO = {}

/**
 * @param {*} server
 * @description "chat server"
 */
function getSocketIO(server) {
    socketIO.io = require("socket.io")(server)
    const io = socketIO.io
    
    io.on("connection", socket => {
        console.log("服务器已连接...", socket.id);
        // 监听所有的用户
        io.sockets.emit("addUser", {uId: socket.id, code: "欢迎新用户的加入..."})

        // 接收登录事件
        socket.on("login", async function(data) {
            // 先判断是否已经有人在登录，是则将其断开连接
            let sql1 = "select * from `userlist` where `isOnline`=? and `username`=?"
            let result = await base(sql1, [1, data.username])
            if(result.length > 0) {
                /* 以后项目要传入登录IP，设备，告诉原用户在哪里被登陆 */
                socket.to(result[0].socketId).emit("logout", {
                    status: "304",
                    code: "账号现在其他设备登录，你已被强制下线",
                    socketId: socket.id,
                    equipment: data.equipment
                })
            }
            // 更新数据
            let sql = 'update `userlist` set `socketId`=?,`isOnline`=?,`equipment`=? where `username`=?';
            let info = await base(sql, [socket.id, 1, data.equipment, data.username])
            if(info.affectedRows) {
                socket.emit("login", {status: 200,code: "登录成功!"})

                // 用户列表
                let list = await base("select * from `userlist`")
                io.sockets.emit("users", Array.from(list))

                // 接收最新的消息(自己未读取的信息)
                let unreceivedSql = "select * from `chatcontent` where `isRead`=? and `to`=?"
                let unreceivedList = await base(unreceivedSql, [0, data.username])
                socket.emit("unreceived", Array.from(unreceivedList))

                // 获取所有群聊（默认是全部都加入了）
                let sql = "select * from `userlist` where `isGroup`=?"
                let group = await base(sql, [1])
                Array.from(group).forEach(item => {
                    // 加入群聊
                    socket.join(item.socketId)
                })
            } else {
                socket.emit("login", {status: 403, code: "登录失败"})
            }
        })

        socket.on('users',async function(){
            let sqlStr = "select * from `userlist`"
            //等待获取mysql查询结果
            let result = await base(sqlStr)
            socket.emit('users', Array.from(result))
        })

        // 接收客户端发送聊天信息
        socket.on("sendMsg", async function(data) {
            let sql = "select * from `userlist` where `username`=? and `isOnline`=?"
            let resTo = await base(sql, [data.to.username, 1])
            if(resTo.length > 0) { /* 判断对方是否在线 */
                // 在线，直接发送消息
                socket.to(resTo[0].socketId).emit("msgInfo", data)
                // 将聊天的内容存放在数据库中 chatcontent
                let sql = "insert into `chatcontent` (`from`, `to`, `chatInfo`, `isRead`, `chatTime`) values (?,?,?,?,?)"
                let _data = [data.from.username, data.to.username, data.chatInfo, 1, data.chatTime]
                base(sql, _data)
            } else {
                // 对方不在线
                let sql = "insert into `chatcontent` (`from`, `to`, `chatInfo`, `isRead`, `chatTime`) values (?,?,?,?,?)"
                let _data = [data.from.username, data.to.username, data.chatInfo, 0, data.chatTime]
                base(sql, _data)
            }
        })

        // 读取消息
        socket.on("readNewMsg", data => {
            let sql = "update `chatcontent` set `isRead`=? where `from`=? and `to`=?"
            base(sql, [1, data.msgOfOtherUser, data.self])
        })

        // 断开连接
        socket.on('disconnect', async () => {
            console.log("断开连接...disconnect", )
            //修改数据库登录信息（socketId,isOnline）
            let sqlStr = "update userlist set socketId=?, isOnline=? where socketId=?"
            await base(sqlStr,[null, 0, socket.id])
        })
    })
}

socketIO.getSocketIO = getSocketIO
module.exports = socketIO